package main

import (
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

//  go get -u gorm.io/gorm
// github.com/go-gorm/sqlite
// gorm.io/driver/sqlite
// gorm.io/gorm

type AFiles struct {
	gorm.Model
	ID      uint `gorm:"primary_key;auto_increment"`
	OldName string
	Name    string
	Size    int
	//CreateDt time.Time
}

var db *gorm.DB

func DBInit() {
	//创建一个db
	db, _ = gorm.Open(sqlite.Open("images.db"), &gorm.Config{})
	//if err != nil {
	//	panic("failed to connect database")

	db.AutoMigrate(&AFiles{}) //构建表
	//defer db.DB()
}
func DBSaveItem(oldname string, path string, size int) {
	db.Create(&AFiles{OldName: oldname, Name: path, Size: size})
}
func DBQueryLast(limit int) []AFiles {
	var files []AFiles
	//db.Model(&AFiles{}).Limit(limit).Find(&files)
	db.Model(&AFiles{}).Order("id desc").Find(&files).Limit(limit)
	return files
}
func DBQueryById(id int) AFiles {
	var file AFiles
	db.Model(&AFiles{}).Where("id = ?", id).First(&file)
	return file
}

func DBUpdateOldName(id uint, oldname string) {
	db.Updates(AFiles{ID: id, OldName: oldname})
}

func DBDeleteItem(id int) {
	db.Delete(&AFiles{}, id)
}
